package book.dao.reader.impl;

import book.dao.reader.ReaderDao;
import book.util.DbHelper;
import book.exception.SystemBookDbException;
import book.pojo.Reader;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;


import java.sql.SQLException;

public class ReaderDaoImpl implements ReaderDao {
    @Override
    public Reader findReaderByUserName(String username) {
        try {
            Reader reader = null;
            //1、创建Query对象，将数据源对象为参数，runner内部使用完连接会自动返回连接池
            QueryRunner runner = new QueryRunner(DbHelper.getDataSource());
            //2、编写sql
            String sql = "select * from reader where username=?";
            //3、执行查询
            reader = runner.query(sql,new BeanHandler<Reader>(Reader.class),username);
            if(reader == null){
                String sql2 = "select * from admin where username=?";
                reader = runner.query(sql2,new BeanHandler<Reader>(Reader.class),username);
            }
            return reader;
        } catch (SQLException e) {
            throw new SystemBookDbException("根据id用户错误："+e.getMessage());
        }
    }

    @Override
    public int addReader(Reader reader) {
        int row = 0;
        //1、创建Query对象，将数据源对象为参数，runner内部使用完连接会自动返回连接池
        QueryRunner runner = new QueryRunner(DbHelper.getDataSource());
        String sql = "insert into reader(name,username,password,salt) values(?,?,?,?)";
        String []org={reader.getName(),reader.getUsername(),reader.getPassword(),reader.getSalt()};
        try {
            row = runner.update(sql,org);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return row;
    }
}
